import { CustomerService } from './../../../@core/services/customer/customer.service';
import { Component, ViewChild } from '@angular/core';
import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { UserService } from 'src/app/@core/services/user/user.service';
import { Router } from '@angular/router';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { AddCustomerTypesComponent } from './add-customer-types/add-customer-types.component';
import { EditCustomerTypeComponent } from './edit-customer-type/edit-customer-type.component';
@Component({
  selector: 'app-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.scss']
})
export class CustomerComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  pageSizeOptions = [10, 20, 30, 50, 100];
  treeData: any;
  checkedIds = [];
  msgs: Array<Object> = [];
  option: any;
  customerTypeId: any;//客户类型id
  pathPids = []//树结构路径
  config = {
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  searchValue = ''
  filteredTreeNodes: any
  displayTreeData: any[];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '客户代号',
        fieldType: 'text',
        fixedLeft: '270px'
      },
      {
        field: 'name',
        header: '客户名称',
        fieldType: 'text',
        fixedLeft: '420px'
      },
      {
        field: 'workCode',
        header: '客户简称',
        fieldType: 'text'
      },
      {
        field: 'account',
        header: '英文名称',
        fieldType: 'text'
      },
      {
        field: 'departmentName',
        header: '类别',
        fieldType: 'text'
      },
      {
        field: 'isLeader',
        header: '客户类型',
        fieldType: 'boolean'
      },
      {
        field: 'station',
        header: '内外销售',
        fieldType: 'text'
      },
      {
        field: 'gender',
        header: '业务员',
        fieldType: 'text'
      },
      {
        field: 'mobile',
        header: '联系人',
        fieldType: 'text'
      },
      {
        field: 'bankName',
        header: '电话',
        fieldType: 'text'
      },
      {
        field: 'bankHolder',
        header: '联系地址',
        fieldType: 'text'
      },
      {
        field: 'bankAccount',
        header: '交货地址',
        fieldType: 'text'
      },
      {
        field: 'wechat',
        header: '传真',
        fieldType: 'text'
      },
      {
        field: 'contractStartDate',
        header: '邮箱',
        fieldType: 'text'
      },
      {
        field: 'idNumber',
        header: '是否开票',
        fieldType: 'text'
      },
      {
        field: 'email',
        header: '营业税率',
        fieldType: 'text'
      },
      {
        field: 'homeAddress',
        header: '扣税类别',
        fieldType: 'text'
      },
      {
        field: 'insuranceState',
        header: '收款账期',
        fieldType: 'text'
      },
      {
        field: 'isStay',
        header: '结算方式',
        fieldType: 'boolean'
      },
      {
        field: 'salaryType',
        header: '交易币种',
        fieldType: 'text'
      },

      {
        field: 'contractEndDate',
        header: '信用额度',
        fieldType: 'text'
      },
      {
        field: 'terminationDate',
        header: '账户结余',
        fieldType: 'text'
      },
      {
        field: 'enabled',
        header: '备注',
        fieldType: 'boolean',
      },
      {
        field: 'enabled',
        header: '创建时间',
        fieldType: 'boolean',
      },
      {
        field: 'contractStartDate',
        header: '状态',
        fieldType: 'text',
        fixedRight:'0px'
      },
    ]
  };//表头数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '40px'
    },
    {
      field: '操作',
      width: '230px'
    },
    {
      field: '客户代号',
      width: '150px'
    },
    {
      field: '客户名称',
      width: '200px'
    },
    {
      field: '客户简称',
      width: '150px'
    },
    {
      field: '英文名称',
      width: '150px'
    },
    {
      field: '类别',
      width: '150px'
    },
    {
      field: '客户类型',
      width: '150px'
    },
    {
      field: '内外销售',
      width: '150px'
    },
    {
      field: '业务员',
      width: '150px'
    },
    {
      field: '联系人',
      width: '150px'
    },
    {
      field: '电话',
      width: '150px'
    },
    {
      field: '联系地址',
      width: '280px'
    },
    {
      field: '交货地址',
      width: '280px'
    },
    {
      field: '传真',
      width: '150px'
    },
    {
      field: '邮箱',
      width: '150px'
    },
    {
      field: '是否开票',
      width: '150px'
    },
    {
      field: '营业税率',
      width: '150px'
    },
    {
      field: '扣税类别',
      width: '150px'
    },
    {
      field: '收款账期',
      width: '150px'
    },
    {
      field: '结算方式',
      width: '150px'
    },
    {
      field: '交易币种',
      width: '150px'
    },
    {
      field: '状态',
      width: '150px'
    },
    {
      field: '信用额度',
      width: '150px'
    },
    {
      field: '账户结余',
      width: '150px'
    },
    {
      field: '备注',
      width: '150px'
    },
    {
      field: '创建时间',
      width: '160px'
    }
  ];//表格宽度配置
  statusoptions = [
   "全部","启用","禁用"
  ]
  statusvalue = {}
  staffNameoptions = [

  ]
  staffNamevalue = null
  customerTypeoptions = ['潜在客户', '真实客户']
  customerTypevalue = ''
  tabledata = []
  @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
  @ViewChild(DataTableComponent, { static: true }) datatable!: DataTableComponent;
  //获取table
  displayTableData: any[];
  Status!: string;
  file: any;
  filter = {
    PageSize: 20,
    PageNumber: 1,
    SearchTerm: '',
    SearchStatus: '',
    SearchCustomerType: '',
    SalesmanId: '',
    CustomerClassId:'',
  }
  searchDepartmentValue: any;
  constructor(private dialogService: DialogService, private UserService: UserService, private Router: Router, private SharedMethodService: SharedMethodService, private CustomerService: CustomerService,private DialogService:DialogService) { }
  ngOnInit(): void {
    this.UserService.GetAllEmploy(this.pager.pageIndex, this.pager.pageSize).subscribe((data: any) => {
      this.staffNameoptions = data.items.map(employee => ({
        id: employee.id,
        name: employee.name
    }));
      console.log(this.staffNameoptions)
    })
    this.CustomerService.GetPagedCustomerClassWithSub(1, 1000).subscribe((data: any) => {
      this.treeData = data
      this.displayTreeData = [{ customerClassName: '全部', customerClassId: null }, ...this.treeData];
    })
    this.search()
  }
  valueChange($event: any) {
    if($event){
      this.filter.SalesmanId = $event.id
    }
  }
  afterTreeInit($event: any) {
    this.setActiveTitleToAll($event);
  }//树形菜单初始化
  setActiveTitleToAll(data: any): void {
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            const item = data[key];
            if (item.data.title === "全部") {
                item.data.isActive = true;
            }
            if (item.data.children && item.data.children.length > 0) {
                this.setActiveTitleToAll(item.data.children);
            }
        }
    }
  }
  getPathPids(node: { customerClassId: any; subCustomerClasses: any; }, targetId: any, path = []) {
    if (node.customerClassId === targetId) {
      return [...path, node.customerClassId];
    }
    if (node.subCustomerClasses) {
      for (let subNode of node.subCustomerClasses) {
        const subPath = this.getPathPids(subNode, targetId, [...path, node.customerClassId]);
        if (subPath) {
          return subPath;
        }
      }
    }
    return null;
  } //获取树形菜单pid的路径
  traverse(node: any, id: any, path = []) {
    path.push(node.customerClassId);
    if (node.customerClassId === id) {
      return path;
    }
    for (let child of node.subCustomerClasses) {
      let result = this.traverse(child, id, [...path]);
      if (result) {
        return result;
      }
    }
    return null;
  }
  nodeSelected($event: any) {
    this.option = $event.data.originItem
    this.customerTypeId = $event.data.originItem.customerClassId;
    this.filter.CustomerClassId = this.customerTypeId
    this.search()
    for (let node of this.treeData) {
      console.log(node, this.customerTypeId)
      const path = this.getPathPids(node, this.customerTypeId);
      if (path) {
        this.pathPids = path;
        console.log(this.pathPids)

        break;
      }else{
        this.pathPids = []
      }
    }
  }//树形菜单点击事件
  creatType(dialogtype?: string) {
    let data = {
      options: this.treeData,
      pathPids: this.pathPids && this.pathPids[0] !== null ? this.pathPids : [],
      display: false
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '新建类别',
      data: data,
      content: AddCustomerTypesComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.form.customerClassName){
              this.CustomerService.CreateCustomerClass(results.modalContentInstance.form).subscribe((data: any) => {
                this.CustomerService.GetPagedCustomerClassWithSub(1, 1000).subscribe((data: any) => {
                  this.treeData = data
                  this.displayTreeData = [{ customerClassName: '全部', customerClassId: null }, ...this.treeData];
                  results.modalInstance.hide();
                  this.showToast('success', '成功', '新建成功')
                })
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
            )
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//新建
  editType(dialogtype?: string) {
    if (this.customerTypeId) {
      let data = {
        options: this.treeData,
        pathPids: this.pathPids.slice(0, -1),
        display: false,
        option: this.option
      };
      const results = this.dialogService.open({
        id: 'department',
        ...this.config,
        title: '编辑部门',
        data: data,
        content: EditCustomerTypeComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if (results.modalContentInstance.form.customerClassName) {
                this.CustomerService.UpdateCustomerClass(this.customerTypeId, results.modalContentInstance.form).subscribe((data: any) => {
                  this.CustomerService.GetPagedCustomerClassWithSub(1, 1000).subscribe((data: any) => {
                    this.treeData = data
                    this.displayTreeData = [{ customerClassName: '全部', customerClassId: null }, ...this.treeData];
                    results.modalInstance.hide();
                    this.showToast('success', '成功', '新建成功')
                  },(error) => {
                    if(error.status==404){
                      this.showToast('error', '失败', '服务器连接失败');
                    }else{
                      this.showToast('error', '失败', error.error);
                    }
                  }
                )
                })
                results.modalInstance.hide();
              }
              data.display = true;
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }//编辑
  deleteType(dialogtype?: string) {
    if (this.customerTypeId) {
      const results = this.dialogService.open({
        ...this.config,
        title: '删除',
        content: '确认删除该分类？',
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              this.CustomerService.DeleteCustomerClass(this.customerTypeId).subscribe((data: any) => {
                  results.modalInstance.hide();
                  this.showToast('success', '成功', '删除成功')
                  this.checkedIds = [];
                  this.CustomerService.GetPagedCustomerClassWithSub(1, 1000).subscribe((data: any) => {
                    this.treeData = data
                    this.displayTreeData = [{ customerClassName: '全部', customerClassId: null }, ...this.treeData];
                  })
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
            )
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }//删除
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  searchDepartment($event: any) {
    this.searchDepartmentValue = $event.target.value
    if (this.searchDepartmentValue === '') {
      this.displayTreeData = [{ customerClassName: '全部', customerClassId: null }, ...this.treeData];
    }else{
      this.filteredTreeNodes = this.filterCategories(this.treeData, this.searchDepartmentValue);
      this.displayTreeData = this.filteredTreeNodes
      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
    }
  }//搜索部门
  pageIndexChange($event: any) {
    this.search()
  }//切换页码
  pageSizeChange($event: any) {
    this.search()
  }//改变每页显示数量
  disable(id:any) {
    this.CustomerService.UnEnableCustomer(id).subscribe((data: any) => {
      this.showToast('success', '成功', '禁用成功')
      this.search()
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//禁用
  enable(id:any) {
    this.CustomerService.EnableCustomer(id).subscribe((data: any) => {
      this.showToast('success', '成功', '启用成功')
      this.search()
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//启用
  deleteCustomers( dialogtype?: string ) {
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该客户？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.CustomerService.DeleteBatchCustomer(this.checkedIds).subscribe((data: any) => {
              this.showToast('success', '成功', '删除成功')
              this.search()
              results.modalInstance.hide();
            },(error) => {
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
              results.modalInstance.hide();
            }
          )
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//删除
  deleteCustomer(id:any, dialogtype?: string ) {
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该客户？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.CustomerService.DeleteBatchCustomer([id]).subscribe((data: any) => {
              this.showToast('success', '成功', '删除成功')
              this.search()
              results.modalInstance.hide();

            },(error) => {
              if(error.status==404){
                this.showToast('error', '失败', '服务器连接失败');
              }else{
                this.showToast('error', '失败', error.error);
              }
              results.modalInstance.hide();
            }
          )
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//删除
  editCustomer(rowitem: any) {
    this.Router.navigate(['/pages/basicdata/customer/edit',rowitem.customerId])
  }//编辑
  search() {
    this.CustomerService.GetPagedCustomer(this.filter).subscribe((data: any) => {
      this.tabledata = data.items
      this.pager.total = data.totalCount
    })
  }//搜索
  search2() {
    this.filter.PageNumber = 1
    this.CustomerService.GetPagedCustomer(this.filter).subscribe((data: any) => {
      this.tabledata = data.items
      this.pager.total = data.totalCount
    })
  }//搜索
  reset() {
    this.filter = {
      PageSize: 20,
      PageNumber: 1,
      SearchTerm: '',
      SearchStatus: '',
      SearchCustomerType: '',
      SalesmanId: '',
      CustomerClassId:'',
    }
    this.staffNamevalue = null
   this.search()
  }//重置
  DownloadUserFileModel() {
    this.CustomerService.DownloadCustomerFileModel().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '客户信息导入模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }//下载模板
  @ViewChild('fileInput1') fileInput1: any;
  @ViewChild('fileInput2') fileInput2: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput1.nativeElement.click();
  }
  onButtonClick2() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput2.nativeElement.click();
  }
  onFileSelected(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.CustomerService.importCustomerFromExcel(this.file).subscribe((data: any) => {
      this.fileInput1.nativeElement.value = '';
      this.showToast('success', '成功', '导入成功')
      this.search()
    },
    (error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//导入员工
  DownloadUserFile() {
    this.CustomerService.DownloadCustomerFile().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '客户信息.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable, 'customerId').subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//获取选中行
  cleared() {
    this.SharedMethodService.cleared(this.checkedIds, this.tabledata, this.datatable).subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//清空选中行
  DownloadDepartmentFileModel() {
    this.CustomerService.DownloadCustomerClassFileModel().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '客户类别导入模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    })
  }
  ImportDepartmentsFromExcel(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.CustomerService.importCustomerClassFromExcel(this.file).subscribe((data: any) => {
      this.fileInput2.nativeElement.value = '';
      this.showToast('success', '成功', '导入成功')
      this.CustomerService.GetPagedCustomerClassWithSub(1, 1000).subscribe((data: any) => {
        this.treeData = data
        this.displayTreeData = [{ customerClassName: '全部', customerClassId: null }, ...this.treeData];
      }
    )
    },error => {
      if (error.status === 404) {
          this.showToast('error', '导入失败', '服务器连接失败');
      } else {
          this.showToast('error', '导入失败', error.error);
      }
      this.fileInput2.nativeElement.value = '';
    }
    )
  }//导入部门
  addCustomer() {
    this.Router.navigate(['/pages/basicdata/customer/add'])
  }//新增员工
  filterCategories(departments: any[], keyword: string): any[] {
    const result: any[] = [];
    for (const department of departments) {
      if (department.customerClassName.includes(keyword)) {
        result.push(department);
      }
      if (department.subCustomerClasses.length > 0) {
        const filteredSubCategories = this.filterCategories(department.subCustomerClasses, keyword);
        if (filteredSubCategories.length > 0) {
          result.push(...filteredSubCategories);
        }
      }
    }
    return result;
  }
  setOpenTrue = (node: { open: boolean; subCustomerClasses: any[]; }) => {
    // 为当前节点添加 open: true 属性
    node.open = true;
    // 如果当前节点有子节点，递归处理子节点
    if (Array.isArray(node.subCustomerClasses)) {
      node.subCustomerClasses = node.subCustomerClasses.map(this.setOpenTrue);
    }
    return node;
  }
}
